#
# Copyright 2010 Steve Leach
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users

from datetime import datetime 

from handlers import EveOpsHandler
from formatting import format_thousands
from evedata import EveData, get_eve_data
from eveoperation import EveOperation, Pilot, MultiPay

class PilotISK():
	pass

def compare_pilot_isk(p1, p2):
	return int(p2.isk) - int(p1.isk)

def add_payment_mappings(mappings):
  	mappings.append(('/multipay', MultiPayHandler))
  	mappings.append(('/multipaid', MultiPaidHandler))
	mappings.append(('/paidopsexport', PaidOpsExportHandler))

class MultiPaidHandler(EveOpsHandler):
	def post(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return

		op_ids = self.request.get('op_ids')

		for op_key in op_ids.split(' '):
			if op_key:
				op = db.get(op_key)
				if op.isk > 0:
					op.paid = True
					op.pay_date = datetime.now()
					op.put()

		self.redirect('/?showpaid=True')

def calc_pilot_payments(ops):
	pilot_isk = {}
	pilot_ops = {}
	for op in ops:
		for pilot in op.pilots:
			if pilot not in pilot_isk:
				pilot_isk[pilot] = 0
				pilot_ops[pilot] = 0
			pilot_ops[pilot] = pilot_ops[pilot]+1
			if pilot == op.fc:
				pilot_isk[pilot] = pilot_isk[pilot] + op.fc_isk()
			else:
				pilot_isk[pilot] = pilot_isk[pilot] + op.pilot_isk()
	return pilot_ops, pilot_isk
				
class MultiPayHandler(EveOpsHandler):
	def get(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		unpaid = EveOperation.gql('WHERE paid = False AND locked = True AND deleted_op = False ORDER BY name')

		pilot_isk = {}
		pilot_ops = {}
		corp_isk = 0
		total_isk = 0

		all_ops = ''

		pilot_ops, pilot_isk = calc_pilot_payments(unpaid)

		for op in unpaid:
			total_isk = total_isk + op.isk
			corp_isk = corp_isk + op.corp_isk()
			all_ops = all_ops + str(op.key()) + ' '

		all_ops = all_ops.strip()
					
		pilot_isk_1 = []
		for name, isk in pilot_isk.items():

			p_i = PilotISK()
			p_i.name = name
			p_i.isk = isk
			p_i.isk_000 = format_thousands(int(isk))
			p_i.ops = pilot_ops[name]

			p = Pilot.gql("WHERE char_name = :1", name).get()
			if not p:
				p = Pilot()
				p.char_name = name
			
			p_i.pilot = p

			pilot_isk_1.append( p_i )

		pilot_isk_1.sort(compare_pilot_isk)

		total_isk = format_thousands(int(total_isk))

		values = {'unpaid': unpaid, 'pilot_isk': pilot_isk_1, 'corp_isk': format_thousands(int(corp_isk)), 'op_ids': all_ops, 'total_isk': total_isk, 'eve_data': eve_data, 'headers': self.request.headers}

		self.display_page( 'multipay.html', values )


class PaidOpsExportHandler(EveOpsHandler):
	def get(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		ops = EveOperation.all()

		quote = '"'
		comma = ', '

		self.response.headers['Content-Type'] = 'text/plain'

		self.response.out.write('Name, ')
		self.response.out.write('ISK, ')
		self.response.out.write('FC, ')
		self.response.out.write('Site, ')
		self.response.out.write('System, ')
		self.response.out.write('Pilots, ')
		self.response.out.write('Date ')
		self.response.out.write('\n')

		for op in ops:
			if op.paid and (op.isk > 0):
				#op_text = quote + op.name + quote + comma + str(op.isk) + comma + op.fc + comma + op.site_type + comma + op.system + comma + str(len(op.pilots)) + comma + str(op.op_date)
				self.response.out.write(quote + op.name + quote)
				self.response.out.write(comma)
				self.response.out.write(str(op.isk))
				self.response.out.write(comma)
				self.response.out.write(op.fc)
				self.response.out.write(comma)
				self.response.out.write(op.site_type)
				self.response.out.write(comma)
				self.response.out.write(op.system)
				self.response.out.write(comma)
				self.response.out.write(len(op.pilots))
				self.response.out.write(comma)
				self.response.out.write(op.op_date)
				self.response.out.write('\n')
			

